<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace addons\news\model;

/**
 * Description of Comment
 * 评论
 * @author shilinqing
 */
class Comment extends \web\common\model\BaseModel {
    
    protected function _initialize() {
        $this->tableName = 'comment';
    }
    
     public function getTwoDepthComments($content_id, $content_type = 0, $pageIndex = -1, $pageSize = -1, $user_id = 0){
        $u = new \addons\member\model\MemberAccountModel();
        $where['content_type'] = $content_type;
        $where['content_id'] = $content_id;
        $where['pid'] = 0;
        $this->where($where);
        if ($pageIndex > 0 && $pageSize > 0) {
            $offset = 0;
            if ($pageIndex > 0)
                $offset = (intval($pageIndex) - 1) * intval($pageSize);
            $this->limit($offset, $pageSize);
        }
        $sql = $this->fetchSql(1)->select();
        $is_like_fileds = '';
        if($user_id > 0){
            $is_like_fileds = ",if(c.id,'1',0) as is_like";
        }
        $sql = 'select a.*, b.username,b.head_img '.$is_like_fileds.' from (' . $sql . ') a left join ' . $u->getTableName() . ' b on a.user_id=b.id';
        if($user_id > 0){
            $likeM = new \addons\news\model\CommLikeRecord();
            $sql .= ' left join '.$likeM->getTableName().' c on c.user_id='.$user_id.' and FIND_IN_SET(a.id,comment_ids)';
        }
        $list = $this->query($sql);
        foreach($list as $k => $v){
            $fields = 'a.*,b.username,b.head_img';
            $where1['content_id'] = $content_id;
            $where1['a.pid'] = $v['id'];
            $this->alias('a')->where($where1)
                    ->join($u->getTableName().' b', 'a.user_id=b.id', 'left');
            if($user_id > 0){
                $fields .= $is_like_fileds;
                $this->join($likeM->getTableName().' c','c.user_id='.$user_id.' and FIND_IN_SET(a.id,comment_ids)','left');
            }
            $list[$k]['children'] = $this->field($fields)->select();
        }
        return $list;
        
    }
}
